//
//  SignForViewController.m
//  LogisticsFollow
//
//  Created by Faith on 2017/2/18.
//  Copyright © 2017年 manridy. All rights reserved.
//

#import "SignForViewController.h"
#import "SignForViewTableViewCell.h"
#import "OrderModel.h"
#import <CoreLocation/CoreLocation.h>

@interface SignForViewController () <UITableViewDelegate ,UITableViewDataSource , UINavigationControllerDelegate, UIImagePickerControllerDelegate >
{
    CLLocationManager *_locationManager;
    BOOL _haveUploadImage;
}
@property (weak, nonatomic) IBOutlet UIImageView *picPickImageView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *signForButton;
@property (nonatomic ,strong) MBProgressHUD *hud;
@property (nonatomic ,strong) UITextField *noteInfoField;

@end

@implementation SignForViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.tableView registerNib:[UINib nibWithNibName:@"SignForViewTableViewCell" bundle:nil] forCellReuseIdentifier:@"signFor"];
    self.picPickImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(takePic)];
    [self.picPickImageView addGestureRecognizer:tap];
    
    self.picPickImageView.layer.cornerRadius = 5;
    self.picPickImageView.layer.masksToBounds = YES;
    self.picPickImageView.layer.borderColor = kUIColorFromHEX(0xaaaaaa, 1).CGColor;
    self.picPickImageView.layer.borderWidth = 1;
    
    self.signForButton.layer.cornerRadius = 5;
    self.signForButton.layer.masksToBounds = YES;
    
    _haveUploadImage = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//选取照片
- (void)takePic
{
    UIAlertController *ac = [[UIAlertController alloc] init];
    [ac addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
        ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
        ipc.allowsEditing = NO;
        ipc.delegate = self;
        [self presentViewController:ipc animated:YES completion:nil];
    }]];
    [ac addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
        ipc.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        ipc.allowsEditing = NO;
        ipc.delegate = self;
        [self presentViewController:ipc animated:YES completion:nil];
    }]];
    [ac addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:ac animated:YES completion:nil];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.noteInfoField endEditing:YES];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo
{
    self.hud = [MBProgressHUD showHUDAddedTo:picker.view animated:YES];
    self.picPickImageView.image = image;
    self.picPickImageView.contentMode = UIViewContentModeScaleToFill;
    
    //上传图片
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
//    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:kImageUploadPort parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        UIImage *newImage = [self thumbnailWithImageWithoutScale:image size:CGSizeMake(300,400)];
        NSData *newData = UIImagePNGRepresentation(newImage);
        [formData appendPartWithFileData:newData name:@"file" fileName:@"iOS_test.JPG" mimeType:@"image/jpeg"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //打印下上传进度
        NSLog(@"上传进度");
        NSLog(@"%@",uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //上传成功
        NSLog(@"上传成功");
        NSDictionary *responseData;
        NSError *error = nil;
        if (responseObject) {
            _haveUploadImage = YES;
            responseData = [NSJSONSerialization JSONObjectWithData:responseObject
                                                           options:NSJSONReadingMutableContainers
                                                             error:&error];
            [self.parametersDic setObject:@(1) forKey:@"endtype"];
            [self.parametersDic setObject:[responseData objectForKey:@"result"] forKey:@"endattach"];
        }
        [self.hud hideAnimated:YES];
        NSLog(@"%@",responseData);
        [picker dismissViewControllerAnimated:YES completion:nil];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //上传失败
        NSLog(@"上传失败error == %@",error);
    }];
}
- (IBAction)signOrderInfo:(UIButton *)sender
{
    if (_haveUploadImage) {
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [self.parametersDic setObject:self.noteInfoField.text forKey:@"endcomment"];
        
        //以post的形式提交，POST的参数就是上面的域名，parameters的参数是一个字典类型，将上面的字典作为它的参数
        // 创建信号量
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
        [manager POST:kEndPort parameters:self.parametersDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            // 隐藏系统风火轮
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            
            //json解析
            NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            //转成jsonModel
            NSError *error = [[NSError alloc] init];
            OrderModel *model = [[OrderModel alloc] initWithDictionary:resultDic error:&error];
            NSLog(@"isSuccess = %d\nmsg = %@",model.isSuccess ,model.msg);
            if (model.isSuccess) {
                //result = YES;
                self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                self.hud.label.text = @"提交成功";
                [self.hud hideAnimated:YES afterDelay:2];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    //上传成功回调，完成main界面刷新
                    self.completeUploadOrderInfoBlock ();
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }else {
                [self doFailPOST];
            }
            dispatch_semaphore_signal(semaphore);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            // 解析失败隐藏系统风火轮(可以打印error.userInfo查看错误信息)
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            [self doFailPOST];
            //result = NO;
            dispatch_semaphore_signal(semaphore);
        }];
    }else {
        UIAlertController *vc = [UIAlertController alertControllerWithTitle:@"提示" message:@"请先上传图片" preferredStyle:UIAlertControllerStyleAlert];
        [vc addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:vc animated:YES completion:nil];
    }
}

- (void)doFailPOST
{
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.mode = MBProgressHUDModeText;
    self.hud.label.text = @"请求失败，请确认网络后重试";
    [self.hud hideAnimated:YES afterDelay:1.5];
}

#pragma mark - UITableViewDelegate && UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SignForViewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"signFor"];
    if (!cell) {
        cell = [[SignForViewTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"signFor"];
    }http://116.62.43.199/website/server/orderhandler.ashx?action=end
    
    if (indexPath.row == 0) {
        cell.name.text = @"签收类型";
        cell.textField.text = @"正常签收";
        cell.textField.textColor = kUIColorFromHEX(0xeb751d, 1);
        cell.textField.enabled = NO;
        //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if (indexPath.row == 1) {
        cell.name.text = @"备注";
        cell.textField.placeholder = @"请输入备注信息";
        cell.textField.enabled = YES;
        self.noteInfoField = cell.textField;
    }
    
    return cell;
}

#pragma mark - 图片压缩
- (UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize

{
    
    UIImage *newimage;
    
    if (nil == image)
        
    {
        
        newimage = nil;
        
    } else {
        
        CGSize oldsize = image.size;
        
        CGRect rect;
        
        if (asize.width/asize.height > oldsize.width/oldsize.height)
            
        {
            
            rect.size.width = asize.height*oldsize.width/oldsize.height;
            
            rect.size.height = asize.height;
            
            rect.origin.x = (asize.width - rect.size.width)/2;
            
            rect.origin.y = 0;
            
        } else {
            
            rect.size.width = asize.width;
            
            rect.size.height = asize.width*oldsize.height/oldsize.width;
            
            rect.origin.x = 0;
            
            rect.origin.y = (asize.height - rect.size.height)/2;
            
        }
        
        UIGraphicsBeginImageContext(asize);
        
        CGContextRef context = UIGraphicsGetCurrentContext();
        
        CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
        
        UIRectFill(CGRectMake(0, 0, asize.width, asize.height));//clear background
        
        [image drawInRect:rect];
        
        newimage = UIGraphicsGetImageFromCurrentImageContext();
        
        UIGraphicsEndImageContext();
        
    }
    
    return newimage;
}

@end
